import React, { useState, useEffect } from 'react'
import { View, ScrollView } from '@tarojs/components'
// import { Cascader } from '@nutui/nutui-react-taro'
// import province from 'china-area-data'
import Taro, { useRouter } from '@tarojs/taro'
import AddressCard from './AddressCard'
import { Popup, Button } from '@nutui/nutui-react-taro'
import AddressEdit from './AddressEdit'
import { Plus } from '@nutui/icons-react-taro'
import { Address } from 'src/types/address'
import { queryAddressList } from '../../api/address'
import { showLoading, hideLoading } from '@tarojs/taro'
import { setToken } from '../../utils/cookies'
import './index.scss'
const prefix = 'address'
enum EditType {
  ADD = 'ADD',
  EDIT = 'EDIT'
}
const Index = () => {
  const [showBottom, setShowBottom] = useState(false)
  const [addressList, setAddressList] = useState<Array<Address>>([]) // 地址信息
  const [addressInfo, setAddressInfo] = useState<Address>({}) //编辑地址
  const [editType, setEditType] = useState<EditType>(EditType.ADD) // 编辑类型
  const router = Taro.getCurrentInstance().router
  // const params = router?.params || {}
  // 方式1：获取URL参数
  const params = Taro.getCurrentInstance().router?.params
  const { db_man, isAdd = false } = params || {}
  const [data, setData] = useState({})
  // 方式2：监听 postMessage
  if (process.env.TARO_ENV === 'h5') {
    window.addEventListener('message', (e) => {
      const data = JSON.parse(e.data)
      setData(data.id)
    })
  }
  if (db_man) {
    setToken('db_man', db_man)
  }
  const fetchList = async () => {
    showLoading({
      title: '加载中...',
      mask: true // 防止触摸穿透
    })
    try {
      let { data, success } = await queryAddressList({})
      if (success) {
        setAddressList(data)
      }
    } catch (error) {
      // console.log(error)
    } finally {
      hideLoading()
    }
  }
  const onEditAddress = (e: Address) => {
    setAddressInfo(e)
    setEditType(EditType.EDIT)
    setShowBottom(true)
  }
  useEffect(() => {
    fetchList()
  }, [])
  const hanldleData = () => {
    // 在网页中发送消息（需要配合上面的 injectedJavaScript）
    window?.ReactNativeWebView.postMessage(JSON.stringify({
      action: 'BUTTON_CLICKED',
      data: { id: '123', text: '亚楠' }
    }));
  }
  return (
    <View className={`${prefix}`}>
      <ScrollView scrollY className={`${prefix}-content`}>
        {
          addressList.map((item, index) => {
            return <AddressCard isAdd={!!isAdd} onEditAddress={onEditAddress} key={index} item={item}></AddressCard>
          })
        }
        {addressList.length <= 0 && <View className={`${prefix}-empty`}>
          暂无数据~
        </View>}
      </ScrollView>
      {!isAdd && <View className={`${prefix}-footer`}>
        <View className={`${prefix}-btn`}>
          {/* <Button onClick={hanldleData}>发送消息</Button> */}
          <Button icon={<Plus></Plus>} style={{ width: '100%' }} type='success' onClick={() => {
            setShowBottom(true)
            // Taro.navigateTo({
            //   url: '/pages/address/addressEdit/index?id=123' // 携带参数跳转
            // })
          }}>添加地址{params?.id}</Button>

        </View>

      </View>}
      {<Popup
        closeable
        visible={showBottom}
        position="bottom"
        style={{ height: '70%' }}
        title={`${editType === EditType.ADD ? '添加地址' : '编辑地址'}`}
        onClose={() => {
          setAddressInfo({})
          setShowBottom(false)
        }}
      >
        <View>
          <AddressEdit onConfirm={(e) => {
            if (e) {
              setAddressInfo({})
              fetchList()
              setShowBottom(false)
              setEditType(EditType.ADD)
            }
          }} valueInfo={addressInfo || {}} setShowBottom={setShowBottom}></AddressEdit>
        </View>

      </Popup>}
    </View>
  )
}
export default Index;